var express = require('express');
var request = require('supertest');
var bodyParser = require('body-parser');
var session = require('node-weixin-session');
var settings = require('node-weixin-settings');
var nodeWeixinAuth = require('node-weixin-auth');
var nodeWeixinRouter = require('node-weixin-router');
var nodeWeixinMessage = require('node-weixin-message')
var messages = nodeWeixinMessage.messages;
var reply = nodeWeixinMessage.reply;




var wx_config = {
    id:'wxc8113e8d0eb91b92',
    secret:'7c9b74ad8a39a51980bb41fd0bb8984c',
    token:'wtfssd'
}


var store = {
  'wxc8113e8d0eb91b92':{
    'app':wx_config
  }
}

process.env.APP_ID = wx_config.id

settings.registerSet(function (id,key,value,cb) {
  console.log('settings.registerSet',id,key,value)
  store[id][key] = value
  cb(value)

});
settings.registerGet(function (id,key,cb) {
  console.log('settings.registerGet',id,key)
  cb(store[id][key])
});

var accessToken = null
nodeWeixinAuth.tokenize(settings, wx_config, function (error, json) {
  console.log('accessToken',error,json)
  accessToken = json.access_token;
});

var app = express();
var port = 3000


app.use(function(req,res,next){
    console.group('收到请求')
    console.log('url',req.url)
    console.log('method',req.method)
    console.log('query',req.query)
    console.log('params',req.params)
    console.log('body',req.body)
    console.log('==================end=============')
    console.groupEnd('收到请求')
   
    next()
    
})


app.use('/public',express.static('public'))


// nodeWeixinAuth.ACCESS_TOKEN_EXP = 60
// //手动得到accessToken
// nodeWeixinAuth.tokenize(settings, wx_config, function (error, json) {
//     console.log('accessToken',error,json)
//     accessToken = json.access_token;
    
//   });

// 初始化
// 其中‘/wx'是微信的处理前缀地址

// node-weixin的自动接口地址如下：
// 1. auth/ack
//    服务器自动检验地址
// 2. jssdk/config 
//    jssdk的配置请求地址，将会返回配置的json串
// 3. oauth/access
//    Oauth发起请求的地址
// 4. oauth/success
//    OAuth成功后的回调地址
// 5. pay/callback
//    支付成功或者失败的回调地址
// 6. pay/unified
//    统一支付发起的接口，由微信的客户端（包括JSSDK）发起。





app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(bodyParser.text({type:'text/*'}));

app.get('/wx/accesstoken',function(req,res){
  res.json({
    code:0,
    data:{
      accessToken
    }
  })
})



//处理接收消息

//需要通过parse分析消息，然后再通知相应的处理方法，这个代码需要放在ack服务器的返回处理

//接收文本
messages.on.text(function(message, res, cb) {
  console.log('处理接收消息 text',message)
  //message.FromUserName
  //message.ToUserName
  //message.CreateTime
  //message.MsgType
  //message.Content
  //message.MsgId
  console.log('cb',cb)
  var _m = reply.text(message.ToUserName, message.FromUserName, message.Content);
  console.log(_m)

  cb(_m);
  res.send(_m)
});

//接收图片
messages.on.image(function(message, res, cb) {
  console.log('处理接收消息 message')
 //message.FromUserName
 //message.ToUserName
 //message.CreateTime
 //message.MsgType
 //message.PicUrl
 //message.MediaId
 //message.MsgId
  res.send();
  cb();
});

//接收语音
messages.on.voice(function(message, res, cb) {
  console.log('处理接收消息 voice')
  //message.FromUserName
  //message.ToUserName
  //message.CreateTime
  //message.MsgType
  //message.Format
  //message.Recognition
  //message.MediaId
  //message.MsgId
  res.send();
  cb();
});

//接收视频
messages.on.video(function(message, res, cb) {
  console.log('处理接收消息 video')
  //message.FromUserName
  //message.ToUserName
  //message.CreateTime
  //message.MsgType
  //message.ThumbMediaId
  //message.MediaId
  //message.MsgId
  res.send();
  cb();
});

//接收短视频
messages.on.shortvideo(function(message, res, cb) {
  console.log('处理接收消息 shortvideo')
  //message.FromUserName
  //message.ToUserName
  //message.CreateTime
  //message.MsgType
  //message.ThumbMediaId
  //message.MediaId
  //message.MsgId
  res.send();
  cb();
});

//接收位置信息
messages.on.location(function(message, res, cb) {
  //message.FromUserName
  //message.ToUserName
  //message.CreateTime
  //message.MsgType
  //message.Location_X
  //message.Location_Y
  //message.Scale
  //message.Label
  //message.MsgId
  res.send();
  cb();
});

//接收链接
messages.on.link(function(message, res, cb) {
  //message.FromUserName
  //message.ToUserName
  //message.CreateTime
  //message.MsgType
  //message.Title
  //message.Description
  //message.Url
  //message.MsgId
  res.send();
  cb();
});

nodeWeixinRouter.express(settings, session, app, '/wx');

// 微信服务器返回的ack信息是HTTP的GET方法实现的
app.get('/weixin/ack', function (req, res) {
    var data = nodeWeixinAuth.extract(req.query);
   
    nodeWeixinAuth.ack(wx_config.token, data, function (errors, data) {
      if (!errors) {
        res.send(data);
        return;
      }
      switch (error) {
        case 1:
          res.send(errors.INPUT_INVALID);
          break;
        case 2:
          res.send(errors.SIGNATURE_NOT_MATCH);
          break;
        default:
          res.send(errors.UNKNOWN_ERROR);
          break;
      }
    });
  });


nodeWeixinRouter.express(settings, session, app, '/wx');


app.listen(port,()=>console.log(`server is running at ${port}...！`))